package com.example.demo;

import com.google.gson.Gson;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.AsynchronousServerSocketChannel;
import java.nio.channels.AsynchronousSocketChannel;
import java.nio.channels.CompletionHandler;
import java.nio.charset.StandardCharsets;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.Future;

public class AioHttpServer3 {

    public static void main(String[] args) throws IOException {
        AsynchronousServerSocketChannel server = AsynchronousServerSocketChannel.open();
        server.bind(new InetSocketAddress(8080));

        System.out.println("AIO HTTP Server started on port 8080");

        server.accept(null, new CompletionHandler<AsynchronousSocketChannel, Void>() {
            @Override
            public void completed(AsynchronousSocketChannel socket, Void attachment) {
                server.accept(null, this);
                handleClient(socket);
            }

            @Override
            public void failed(Throwable exc, Void attachment) {
                System.out.println("Failed to accept client connection: " + exc.getMessage());
            }
        });

        try {
            System.in.read();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            server.close();
        }
    }

    private static void handleClient(AsynchronousSocketChannel socket) {
        ByteBuffer buffer = ByteBuffer.allocate(1024);
        Future<Integer> readResult = socket.read(buffer);

        try {
            readResult.get();
            buffer.flip();
            String response = "HTTP/1.1 200 OK " +
                    "Content-Length: 13 " +
                    "Content-Type: text/plain " +
                    "Hello, World!";
            Map map = new HashMap<>();
            map.put("code","200");
            map.put("data","hello world~");
            Gson gson = new Gson();
            String s = gson.toJson(map);
            System.out.println(s);
            socket.write(ByteBuffer.wrap(s.getBytes(StandardCharsets.UTF_8))).get();
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                socket.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
}
